package com.example.demo.utils;

import com.example.demo.common.R;
import com.example.demo.config.LoginUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class WebUtils {
    public static ObjectMapper json = new ObjectMapper();

    public static String toJson(Object o) {
        try {
            return json.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
    public static LoginUser getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication.getName().equals("anonymousUser")) {
            return null;
        }
        return (LoginUser)authentication.getPrincipal();
    }
    public static Long getLoginUserId() {
        LoginUser user = getLoginUser();
        return user==null?null:user.getId();
    }
    public static void response(R r, HttpServletResponse response) throws IOException {
        //允许浏览器响应跨域服务器返回的数据
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(json.writeValueAsString(r));
        out.flush(); out.close();
    }
}
